package com.ljs.mywebsoket.webserver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.coyote.http11.filters.VoidInputFilter;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/imserver/{userId}")
@Slf4j

@Component
public class WebSocketServer {
    //连接数
    private static int onlineCount = 0;
    //人数
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
    // /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private  static ConcurrentHashMap<String ,WebSocketServer> webSocketMap=new ConcurrentHashMap<>();
    //会话
    private Session session;
    /**接收userId*/
    private String userId="";
    //打开的时候
    @OnOpen
    public void onopen(Session session,@PathParam("userId") String userId){
        this.session = session;
        this.userId=userId;
        //判断是否已经有了
        if(webSocketMap.containsKey(userId)){
            //移除
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
        }else {
            //如果不在线的话
            webSocketMap.put(userId,this);
            //人数也+1
            addOnlineCount();
        }
        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
        try {
            sendMsg("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("网络异常");
        }
    }
    //发送消息
    public void sendMsg(String msg) throws IOException {
        this.session.getBasicRemote().sendText(msg);

    }

    //接收消息的方法
    @OnMessage
    public void onmsg(String msg,Session session) throws IOException {
        log.info("用户消息:"+userId+",报文:"+msg);
        if(StringUtils.isNoneBlank(msg)){//消息不为空
            //解析发送的报文
            JSONObject jsonObject = JSON.parseObject(msg);
            //追加发送人(防止串改)
            jsonObject.put("fromUserId",this.userId);
           //发送给id
        String  toUserId=   jsonObject.get("toUserId").toString();
        //发送的id 和map里面已经有了
           if(StringUtils.isNoneBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
               //再发送消息
               webSocketMap.get(toUserId).sendMsg(jsonObject.toJSONString());

           }else {
               log.error("要发送的用户不存在");
           }
        }

    }

    @OnError
    //发生错误
    public void erro(Session session,Throwable error){
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }

    @OnClose
    public  void onClose(){
        //关闭
        if(webSocketMap.containsKey(userId)){
            //如果还在的话

            webSocketMap.remove(userId);
            //人数也要减少
            subOnlineCount();

        }
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());

}
    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:"+userId+"，报文:"+message);
        if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMsg(message);
        }else{
            log.error("用户"+userId+",不在线！");
        }
    }


}
